package com.longsec.qq.utils;

import java.util.Map;

import javax.script.Invocable;
import javax.script.ScriptEngine;
import javax.script.ScriptEngineManager;

/**
 * 登入工具
 * @author 		Mr.Huang
 * @version		2019年12月4日
 */
public class LoginUtil {

	/**
	 * 添加Cookie
	 * @param cookies
	 * @param name
	 * @param val
	 */
	public static void addCookie(Map<String, String> cookies,String name,String val){
		cookies.put(name, val);
	}
	
	/**
	 * 组装Cookie
	 * @param cookies
	 * @return
	 */
	public static String getCookies(Map<String, String> cookies){
		StringBuffer buffer = new StringBuffer();
		for (String key : cookies.keySet()) {
			buffer.append(key).append("=").append(cookies.get(key)).append(";");
		}
		return buffer.toString();
	}
	
	/**
	 * 提取Cookie内容
	 * @param cookies
	 * @param name
	 * @return
	 */
	public static String getCookies(Map<String, String> cookies,String name){
		String value = cookies.get(name);
		return value==null?"":value;
	}
	
	/**
	 * 计算验证qrsig
	 * @param cookies
	 * @return
	 * @throws Exception
	 */
	public static String getPtqrtoken(Map<String, String> cookies) throws Exception{
		String qrsig = getCookies(cookies,"qrsig");
		ScriptEngineManager manager = new ScriptEngineManager();
        ScriptEngine engine = manager.getEngineByName("javascript");
        engine.eval("function hash33(t){for(var e=0,i=0,n=t.length;i<n;++i)e+=(e<<5)+t.charCodeAt(i);return 2147483647&e}");
        Invocable in = (Invocable) engine;
        return String.valueOf(in.invokeFunction("hash33",qrsig));
	}
	
	
	/**
	 * 截取字符串中间文本
	 * 如果截取的条件不符合要求就返回原字符串
	 * @param str 待截取的字符串
	 * @param start 开始位置
	 * @param stop  结束位置
	 * @author 黄泽群
	 * @version 2017-05-25
	 * @return
	 */
	public final static String subMiddle(String str,String start,String stop){
		String data = str;
		int startindex = str.indexOf(start);
		//判断是否找了字符串
		if(startindex  == -1){
			return str;
		}
		data = data.substring(startindex+start.length());
		int stopindex = data.indexOf(stop);
		//判断是否找了字符串
		if(stopindex  == -1){
			return str;
		} 
		return data.substring(0,stopindex);
	}
}
